class Queue {
  constructor() {
    this.queue = [];
    this.running = false;
    this.onQueueFinish = null;
  }

  add(fn, ...args) {
    this.queue.push({ fn, args });
    if (!this.running) {
      this.run();
    }
  }

  async run() {
    if (this.queue.length === 0) {
      this.running = false;
      if (this.onQueueFinish) {
        this.onQueueFinish();
      }
      return;
    }

    this.running = true;
    const { fn, args } = this.queue.shift();
    await fn(...args);
    this.run()
  }
  setOnQueueFinish(callback) {
    this.onQueueFinish = callback;
  }
}

export default Queue;
